import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import { config} from '../../shared/smartadmin.config';

declare var $: any;
declare var toMapPoint: any;
@Component({
	selector: 'sa-stopCars-page',
	templateUrl: './stopCars-page.component.html',
	styleUrls: ['./stopCars-page.css']
})
export class StopCarsPageComponent implements OnInit {
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {

			carNumberInput: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择车牌号码'
					}
				}
			},
			lng: {
				validators: {
					notEmpty: {
						message: '请输入经度值'
					}
				}
			},
			lat: {
				validators: {
					notEmpty: {
						message: '请输入纬度值'
					}
				}
			},
			startTime: {
				validators: {
					notEmpty: {
						message: '请输入起始时间'
					},
					date: {
                        format: 'YYYY-MM-DD h:m:s',
                        message: '请输入正确的时间,例如2018-00-00 00:00:00'
                    }

				}
			},
			endTime:{
				validators: {
					notEmpty: {
						message: '请输入结束时间'
					},
					date: {
                        format: 'YYYY-MM-DD h:m:s',
                        message: '请输入正确的时间,例如2018-00-01 00:00:00'
                    }

				}
			}
		}

	}
	
	tableStratTime='';
	tableEndTime='';
	page: any = {
		id: '',
		carNumber:'',
		deviceId:'',
		endTime:'',
		parkingPlace:'',
		startTime:'',
		totalTime:'',
		x:'',
		y:'',

	};
	
	pageType='new';//页面类型,new=新增,updata=编辑
	itemArr : any = [];
	nowPage=1;
	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.nowPage=queryParams.nowPage;
			if(queryParams.itemData){
				this.tableStratTime=queryParams.tableStratTime;
				this.tableEndTime=queryParams.tableEndTime;
				var itemData=JSON.parse(queryParams.itemData);
				this.pageType='updata';
				for(let item in itemData){
					this.page[item]=itemData[item];
				}
			}
		});
	}
	del_carNumber(){
		this.page.carNumber = '';
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberSelect2').val("");
		$("#select2-carNumberSelect2-container").empty();
		$("#select2-carNumberSelect2-container").attr("title","");
		$("#select2-carNumberSelect2-container").prepend(str);
		$("#carNumberInput").val(this.page.carNumber).change();
	}
	onSubmit() {

		$('#fileForm').bootstrapValidator('validate'); //开启验证
		let isValid = $('#fileForm').data('bootstrapValidator').isValid(); //验证是否通过
		if(isValid) {
			this.updata();
		}
	}
	//上传提交
	updata(){
		//计算总停车时长,并且转换成时分秒格式
		if(this.page.startTime!==''&&this.page.endTime!==''){
			let time1=new Date(this.page.startTime).getTime();
			let time2=new Date(this.page.endTime).getTime();
			this.page.totalTime=((time2-time1) / 1000).toString(); //总停车时长单位取秒
		}
		
		//通过地址获取到实际坐标地址
		var point={lng:this.page.x,lat:this.page.y}
		var mapPoint=toMapPoint(point);
		if(!mapPoint){
			this.jsonApiService.message('经纬度不在国内或填写错误.')
			return;
		}
		common.pointGetAdress(mapPoint).then((adress)=>{
			this.page.parkingPlace=adress;
			var reqdata='';
			for (let item in this.page) {
				let value=this.page[item]?this.page[item]:'';
				
				if(reqdata==''){
					reqdata=item+'='+common.stringTrim(value);
				}
				else{
					reqdata=reqdata+'&'+item+'='+common.stringTrim(value);
				}
			}
			this.jsonApiService.http("parkPosition/addOrUpdParkPosition", reqdata).subscribe(result => {
				this.jsonApiService.message(result.message);
				this.router.navigate(['data-statistics/stopCars'],{ queryParams: {nowPage:this.nowPage}});
			})
		})
 
    }

	//	返回资源列表页
	goBack() {
		
		//两种方式,缓存方式
		localStorage.setItem('s_nowPage',this.nowPage.toString());
		localStorage.setItem('s_tableStratTime',this.tableStratTime);
		localStorage.setItem('s_tableEndTime',this.tableEndTime);
		this.router.navigate(['data-statistics/stopCars']);
	}
	ngOnInit() {
		this.initDate().then(()=>{
			if(this.pageType=='updata'){
				$("#datetimepicker2").val(this.page.endTime);
				
				$("#datetimepicker1").val(this.page.startTime);//当前时间
			}
		})
		
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				this.selectCompany().then(()=>{
					if(this.pageType=='updata'){
						$('.select2-selection__placeholder').text(this.page.carNumber).animate({'color':'#555'},10);
					}
					
				});//初始化select 2 车辆
			})

		})
		
		
	}
	
		//初始化日期
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true
						}).on("changeDate", function(e){
							var date = e.date;
							if(!date){return;}
							var time = common.getTimeMmss(date);
							$("#datetimepicker2").datetimepicker("setStartDate", time);
						});
						$("#datetimepicker2").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true
						}).on("changeDate", function(e){
							var date = e.date;
							if(!date){return;}
							var time = common.getTimeMmss(date);
							$("#datetimepicker1").datetimepicker("setEndDate", time);
						});
						var date = new Date();
						var endTime=common.getTimeMmss(date);
						$("#datetimepicker2").val(endTime);
						that.page.endTime=endTime;
						
						date.setDate(date.getDate() - 1);//设置前一天.
						var startTime=common.getTimeMmss(date);
						$("#datetimepicker1").val(startTime);//当前时间
						that.page.startTime=startTime;
						
						resolve();
					});
				}
			);
		})

	}

	//选择公司
	selectCompany() {
		var that = this;
		
		return new Promise(function (resolve, reject) {

		

		$("#carNumberSelect2").select2({
			language: "zh-CN",
			placeholder: "请选择",
			allowClear: true,
			minimumInputLength: 2, //最少2个字符，select2才显示查询的内容

			ajax: {
				url: config.BaseURL + "stats/carListByCarNumber.html",
				dataType: 'json',
				delay: 50,
				method: "POST",
				xhrFields: {
					withCredentials: true
				},
				data: function(params) {
					return {
						"carNumber": params.term // search term
					};
				},
				processResults: function(data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if(data.data.length<=10){
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if(arr.indexOf(car.carNumber)!=-1){
								sameCar.push(car.carNumber)
							}else{
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function(index, car) {
							if(sameCar.indexOf(car.carNumber)!=-1){
								options.push({
									id: car.deviceId,
									text: car.carNumber+"["+car.parentName+"]"
								})
							}else{
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					}else{
						$(data.data).each(function(index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: that.formatRepo
		}).on("select2:select", function(e) {
			var data = e.params.data;
			that.page.deviceId = data.id;
			if(data.text.indexOf('[') > 0){
				that.page.carNumber = data.text.split('[')[0];
			} else {
				that.page.carNumber = data.text;
			}
			$("#carNumberInput").val(that.page.carNumber).change();
		});
		
			resolve();
		})
		
	}
	//select2 格式回调函数
	formatRepo(state) {
		if(!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}

}